package com.jack.screenprojectionplayersimple

import org.java_websocket.client.WebSocketClient
import org.java_websocket.handshake.ServerHandshake
import java.lang.Exception
import java.net.URI
import java.nio.ByteBuffer

/**
 * @创建者 Jack
 * @创建时间 2024/1/13 10:16
 * @描述
 */
class ClientSocket(socketCallback: SocketCallback) {
    private var mSocketCallback: SocketCallback
    private lateinit var mCustomWebSocketClient: CustomWebSocketClient

    init {
        mSocketCallback = socketCallback
    }

    fun init(uri: URI) {
        mCustomWebSocketClient = CustomWebSocketClient(uri)
        mCustomWebSocketClient.connect()
    }

    private inner class CustomWebSocketClient(serverURI: URI) :
        WebSocketClient(serverURI) {

        override fun onOpen(serverHandshake: ServerHandshake) {
            println("CustomWebSocketClient onOpen")
        }

        override fun onMessage(s: String) {}
        override fun onMessage(bytes: ByteBuffer) {
            println("CustomWebSocketClient onMessage ${bytes.remaining()}")
            val buf = ByteArray(bytes.remaining())
            bytes[buf]
            mSocketCallback.callBack(buf)
        }

        override fun onClose(i: Int, s: String, b: Boolean) {
            println("CustomWebSocketClient onClose $i $s $b")
        }

        override fun onError(e: Exception) {
            println("CustomWebSocketClient onError ${e.message}")
        }
    }
}